﻿// Util/ChannelBasedJsonDataManager.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using MultiDAQ_Analysis.Models;

namespace MultiDAQ_Analysis.Util
{
    /// <summary>
    /// 基于通道的JSON数据管理器
    /// </summary>
    public static class ChannelBasedJsonDataManager
    {
        private static readonly string DataDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ChannelMeasurementData");

        static ChannelBasedJsonDataManager()
        {
            try
            {
                // 放到用户 LocalAppData 下
                var baseDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                DataDirectory = Path.Combine(baseDir, "MultiDAQ_Analysis", "ChannelMeasurementData");

                Directory.CreateDirectory(DataDirectory); // 确保存在
            }
            catch (Exception ex)
            {
                // 兜底写临时目录
                DataDirectory = Path.Combine(Path.GetTempPath(), "MultiDAQ_Analysis", "ChannelMeasurementData");
                Directory.CreateDirectory(DataDirectory);
                Console.WriteLine($"[初始化降级] 使用临时目录: {DataDirectory}, 原因: {ex.Message}");
            }
        }

        /// <summary>
        /// 按通道保存多轮测量数据，同类型覆盖
        /// </summary>
        public static async Task SaveMultiRoundDataByChannelAsync(MultiRoundMeasurementData data)
        {
            try
            {
                var tasks = new List<Task>();

                foreach (var channelResult in data.ChannelResults)
                {
                    int channelIndex = channelResult.Key;
                    var channelData = channelResult.Value;

                    // 为每个通道创建独立的数据文件
                    var channelMeasurementData = new ChannelMeasurementFile
                    {
                        ChannelIndex = channelIndex,
                        LastUpdated = DateTime.Now,
                        MeasurementHistory = new Dictionary<string, MultiRoundMeasurementData>()
                    };

                    string fileName = $"Channel_{channelIndex + 1:D2}_Measurements.json";
                    string filePath = Path.Combine(DataDirectory, fileName);

                    // 如果文件存在，先加载现有数据
                    if (File.Exists(filePath))
                    {
                        try
                        {
                            channelMeasurementData = await LoadChannelMeasurementFileAsync(filePath);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"[加载警告] 通道 {channelIndex + 1} 文件加载失败，创建新文件: {ex.Message}");
                            channelMeasurementData = new ChannelMeasurementFile
                            {
                                ChannelIndex = channelIndex,
                                LastUpdated = DateTime.Now,
                                MeasurementHistory = new Dictionary<string, MultiRoundMeasurementData>()
                            };
                        }
                    }

                    // 创建该通道的测量数据副本
                    var singleChannelData = CreateSingleChannelData(data, channelIndex, channelData);

                    // 同类型覆盖：使用测量类型作为key
                    channelMeasurementData.MeasurementHistory[data.MeasurementType] = singleChannelData;
                    channelMeasurementData.LastUpdated = DateTime.Now;

                    // 异步保存
                    tasks.Add(SaveChannelMeasurementFileAsync(filePath, channelMeasurementData));
                }

                await Task.WhenAll(tasks);
                Console.WriteLine($"[通道保存] 所有 {data.ChannelResults.Count} 个通道数据已保存");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[通道保存错误] {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 创建单通道数据
        /// </summary>
        private static MultiRoundMeasurementData CreateSingleChannelData(
            MultiRoundMeasurementData originalData, int channelIndex, ChannelMultiRoundResult channelResult)
        {
            return new MultiRoundMeasurementData
            {
                MeasurementId = originalData.MeasurementId,
                MeasurementType = originalData.MeasurementType,
                StartTime = originalData.StartTime,
                EndTime = originalData.EndTime,
                TotalRounds = originalData.TotalRounds,
                MeasurementTimeMinutes = originalData.MeasurementTimeMinutes,
                Parameters = originalData.Parameters,
                CalculationContext = originalData.CalculationContext,
                ChannelResults = new Dictionary<int, ChannelMultiRoundResult>
                {
                    [channelIndex] = channelResult
                }
            };
        }

        /// <summary>
        /// 保存通道测量文件
        /// </summary>
        private static async Task SaveChannelMeasurementFileAsync(string filePath, ChannelMeasurementFile data)
        {
            var json = JsonConvert.SerializeObject(data, Formatting.Indented);
            using (var writer = new StreamWriter(filePath))
            {
                await writer.WriteAsync(json);
                await writer.FlushAsync();
            }
        }

        /// <summary>
        /// 加载通道测量文件
        /// </summary>
        private static async Task<ChannelMeasurementFile> LoadChannelMeasurementFileAsync(string filePath)
        {
            string json;
            using (var reader = new StreamReader(filePath))
            {
                json = await reader.ReadToEndAsync();
            }
            return JsonConvert.DeserializeObject<ChannelMeasurementFile>(json);
        }

        /// <summary>
        /// 获取通道的特定类型测量数据
        /// </summary>
        public static async Task<MultiRoundMeasurementData> GetChannelMeasurementAsync(int channelIndex, string measurementType)
        {
            try
            {
                string fileName = $"Channel_{channelIndex + 1:D2}_Measurements.json";
                string filePath = Path.Combine(DataDirectory, fileName);

                if (!File.Exists(filePath))
                {
                    return null;
                }

                var channelFile = await LoadChannelMeasurementFileAsync(filePath);
                return channelFile.MeasurementHistory.ContainsKey(measurementType)
                    ? channelFile.MeasurementHistory[measurementType]
                    : null;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[获取数据错误] 通道 {channelIndex + 1}, 类型 {measurementType}: {ex.Message}");
                return null;
            }
        }
    }

    /// <summary>
    /// 通道测量文件结构
    /// </summary>
    public class ChannelMeasurementFile
    {
        [JsonProperty("channelIndex")]
        public int ChannelIndex { get; set; }

        [JsonProperty("lastUpdated")]
        public DateTime LastUpdated { get; set; }

        [JsonProperty("measurementHistory")]
        public Dictionary<string, MultiRoundMeasurementData> MeasurementHistory { get; set; }
    }

}